package org.jdcenter.server.deployment;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdcenter.server.xb.metadata.BeanMateData;
import org.jdcenter.server.xb.metadata.MateData;
import org.jdstream.picocontainer.PluginsPicoContainer;
import org.picocontainer.DefaultPicoContainer;
import org.picocontainer.MutablePicoContainer;
/**
 * @author miao
 * @since 2008-12-04
 *
 */
public class DelegateDeployer implements AbstractDeployer{
	
	protected Log log = LogFactory.getLog(getClass());
	
	private static PluginsPicoContainer pico = new PluginsPicoContainer();
	private static Map<String,AbstractDeployer> deployers = new HashMap<String,AbstractDeployer>();
	private static ConcurrentLinkedQueue<AbstractDeployer> deployers_queue = new ConcurrentLinkedQueue<AbstractDeployer>();
	private static DelegateDeployer dDeployer;
	
	public static DelegateDeployer getInstance(){
		if(dDeployer == null){
			dDeployer = new DelegateDeployer();
		}
		return dDeployer;
	}
	
	public static MutablePicoContainer getPico(){
		if(pico == null){
			pico = new PluginsPicoContainer();
		}
		return pico;
	}
	
	@Override
	public void deploy(MateData mateData) {

		if(mateData instanceof BeanMateData){
			BeanMateData bData = (BeanMateData)mateData;
			if(deployers.containsKey(bData.getBeanName())){
				throw new DeployException("beanName:"+bData.getBeanName()
						+" is already exist");
			}
			BeanDeployer deployer = new BeanDeployer(pico,bData);
			deployers.put(bData.getBeanName(), deployer);
			deployers_queue.add(deployer);
			return;
		}
		throw new DeployException(mateData.getClass().getName()
				+" is not type to deploy");
	}

	@Override
	public void deploy() {
		log.info("start to deploy plugins");
		while(!deployers_queue.isEmpty()){
			deployers_queue.poll().deploy();
		}
		pico.start();
	}
	

	@Override
	public void undeploy() {
		log.info("start to undeploy plugins");
		for(String key:deployers.keySet()){
			deployers.get(key).undeploy();
		}
	}

}
